/*
 * Worker.cpp
 *
 *  Created on: 31-07-2011
 *      Author: cristian
 */

#include "Worker.h"


std::string Worker::getDescripcion() const {
	return descripcion;
}

std::string Worker::getNombre() const {
	return nombre;
}

void Worker::setDescripcion(std::string descripcion) {
	this->descripcion = descripcion;
}

void Worker::setNombre(std::string nombre) {
	this->nombre = nombre;
}

Worker::~Worker() {
	delete this->logger;
}

void Worker::trace() {
#ifdef TRACE
	HAL_TRACE(this->logger, "nombre %s", this->getNombre().c_str());
	HAL_TRACE(this->logger, "descripcion %s", this->getDescripcion().c_str());

//	this->database->printAll();
#endif
}

Worker *Worker::clone(){

	Worker* w = new Worker(this->getId(), this->getNombre(), this->getDescripcion());
	w->setPos(this->getX(), this->getY());
	return w;
}

pthread_attr_t *Worker::getAttr() const
{
    return attr;
}

pthread_t *Worker::getThread() const
{
    return thread;
}

void Worker::setAttr(pthread_attr_t *attr)
{
    this->attr = attr;
}

void Worker::setThread(pthread_t *thread)
{
    this->thread = thread;
}

int Worker::getRun() const
{
    return run;
}

void Worker::setRun(int run)
{
    this->run = run;
}



AmbienteAbstract *Worker::getAmbiente() const
{
    return ambiente;
}

void Worker::setAmbiente(void* ambiente)
{
    this->ambiente = (AmbienteAbstract*)ambiente;
}

void Worker::newPos(unsigned int x, unsigned int y)
{
	this->setPos(x,y);
}

unsigned int Worker::getId() const
{
    return id;
}

void Worker::setId(unsigned int id)
{
    this->id = id;
}

Worker::Worker(unsigned int id, std::string nombre, std::string descripcion)
{

	setNombre(nombre);
	setId(id);
	setDescripcion(descripcion);
	this->logger = new Logger();
	this->thread = new pthread_t;
	this->attr = new pthread_attr_t;
	this->setRun(1);
	pthread_attr_init(attr);
	pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);
}

list<Data*> Worker::getDatos() const
{
    return datos;
}

void Worker::setDatos(list<Data*> datos)
{
    this->datos = datos;
}

void *Worker::start(void *arg) {
	((Worker*) arg)->work(arg);
}

void *Worker::work(void *arg) {

	srand (time(NULL) );
	while(this->getRun()) {
		sleep(rand() % 3);
		bool mover = this->getAmbiente()->move(this->getX(),this->getY(),this->getX()+1,this->getY()+1);
		if (mover){
			this->setPos(this->getX()+1,this->getY()+1);
		}
	}
#ifdef TRACE
	HAL_TRACE(this->logger, "worker %s , stop",this->getNombre().c_str() );
#endif

}

